<?php

namespace app\common\model;

use app\common\service\TimeActivity;
use app\common\service\Upload;
use think\Collection;
use think\facade\Db;
use think\Model;
use think\model\concern\SoftDelete;
use think\Paginator;

class GoodsModel extends BaseModel
{
    use SoftDelete;
    //指定sku数据
    public $sku_id = 0;

    /**
     * @var UserModel
     * */
    public static $user_model = null;

    public static  $fields_type = [
        ['name' => '普通商品'],
    ];
    public static  $fields_mch_status = [
        ['name' => '强制下架'],
        ['name' => '正常'],
    ];



    //数据库表名
    protected $table = 'goods';

    protected $json = ['spu', 'sku'];

    public static $fields_default_spu = [
        ['name' => '品牌', 'value' => ''],
    ];


    //--指定秒杀
    public static $kill_at = -1;

    public function getGroupNoAttr()
    {
        return $this['no'].'-'.$this['code'];
    }

    public function getCustomLogoNumIntroAttr()
    {
        $value = $this['custom_logo_num'];
        if(empty($value)){
            return [];
        }
        return explode('-',$value);
    }

    public function getTagsAttr($value)
    {
//        $data = [];
//        $values = empty($value) ? [] : explode(",",$value) ;
//        foreach ($values as $item){
//            if(empty($item)) continue;
//            $data[] = intval($item);
//        }
        return empty($value)?'': mb_substr($value,1,-1);
    }

    public function setScoreAttr($value)
    {
        $value = empty($value) ? 0 : intval($value);
        if($value>5){
            return 5;
        }
        return $value;
    }


    public function getOgPriceAttr($value)
    {
        $og_price = $value;

        if(app()->http->getName()!='admin'){
            $sold_sku_info = $this['sold_sku_info'];
            if(!empty($sold_sku_info)){
                $og_price = empty($sold_sku_info['og_price'])?"0.00":$sold_sku_info['og_price'];
            }
        }
        return $og_price;

    }


    public function getIsGiftAttr($value)
    {
        $tags = $this->getData('tags');
        if(empty($tags)){
            return 0;
        }
        return stripos($tags,',gift,') === false ? 0 : 1;
    }


    public function getGroupCateIdAttr($value, $data)
    {
        $cid = $data['cid'] ?? '';
        $ct_id = $data['ct_id'] ?? '';
        $str = $cid;
        if (!empty($ct_id)) {
            $str .= ',' . $ct_id;
        }
        return $str . '';
    }

    //商品封面图
    public  function getSerLocationsAttr($value, $data)
    {
        return empty($value) ? [] : explode(',', $value);
    }
    //商品封面图
    public  function getCoverImgAttr($value, $data)
    {
        return empty($this['img']) ? '' : $this['img'][0];
    }
    //商品封面图
    public  function getCoverImgTAttr($value, $data)
    {
        return count($this['img']) < 2 ? $this['cover_img'] : $this['img'][1];
    }


    //组合sku
    public function getSkuAttrImgAttr($value,$data)
    {
        if(app()->http->getName()=='admin'){


            return [];
        }else{
            $sku_price = $this['sku_price'];
            $sku_imgs = [];
            if (!empty($sku_price) ) {
                foreach ($sku_price as $item) {
                    $name_arr = explode(',',$item['name']);
                    $first_name = $name_arr[0]??'';
                    if(empty($sku_imgs[$first_name])){
                        $sku_imgs[$first_name] = $item['img'];
                    }
                }
            }
            return array_values(array_filter($sku_imgs));
        }

    }

    //组合sku
    public function getSkuAttrAttr($value,$data)
    {
        $sku = $this['sku'];
        $sku = empty($sku) ? [] : $sku;
        if(app()->http->getName()=='admin'){

            foreach ($sku as &$vo) {
                $vo['content'] = empty($vo['content']) ? [] : (is_array($vo['content'])?$vo['content']:explode(',',$vo['content']));
            }
            return $sku;
        }else{
            $sku_price = $this['sku_price'];
            $sku_imgs = [];
            if (!empty($sku_price) ) {
                foreach ($sku_price as $item) {
                    $name_arr = explode(',',$item['name']);
                    $first_name = $name_arr[0]??'';
                    if(empty($sku_imgs[$first_name])){
                        $sku_imgs[$first_name] = $item['img'];
                    }
                }
            }
            foreach ($sku as $key=>&$vo){
                $arr = empty($vo['content']) ? [] : (is_array($vo['content'])?$vo['content']:explode(',',$vo['content']));
                $items=[];
                foreach ($arr as $name){
                    $info = [
                        'name'=> $name,
                        'img'=> !empty($sku_imgs[$name]) ? $sku_imgs[$name] : '' ,
                    ];
                    $items[] = $info;
                }


                $vo['content'] = $items;
            }
        }


        return $sku;
    }

    //获取sku信息
    public function getSoldSkuInfoAttr()
    {
        $linkSkuPriceOne = $this->getRelation('linkSkuPriceOne');
        $linkSkuPrice = $this->getRelation('linkSkuPrice');

        $info = null;
        if (!empty($this->sku_id) && !empty($linkSkuPrice) && !$linkSkuPrice->isEmpty()) {
            foreach ($linkSkuPrice as $vo) {
                if ($vo['id'] == $this->sku_id) {
                    $info =  $vo;
                    break;
                }
            }
        } elseif (!empty($linkSkuPriceOne)) {
            return $linkSkuPriceOne;
        }
        return $info;
    }



    //商品实际销售价格
    public function getSoldPriceAttr($value, $data)
    {
        $price = $data['price'];
        if (!empty($this['is_subscribe'])) {
            return $price;
        }
        if (!empty($this['is_kill'])) {
            $kill_price = $data['kill_price'] ?? '0.00';
            $sold_price = empty($this['sold_sku_info']) ? $kill_price : $this['sold_sku_info']['sold_price'];
        } else {
            $sold_price = empty($this['sold_sku_info']) ? $price : $this['sold_sku_info']['sold_price'];
        }
        return sprintf('%.2f', $sold_price);
    }

    //商品实际销售价格
    public function getCalSoldPriceAttr($value, $data)
    {
        if (!empty(self::$user_model) && self::$user_model['type'] > 0) {

            return  $this['sold_vip_price'];
        } else {
            return  $this['sold_price'];
        }
    }

    //商品实际销售价格
    public function getSoldVipPriceAttr($value, $data)
    {
        $price_field = 'price1';
        if (!empty(self::$user_model) && self::$user_model['type'] > 0) {
            $price_field = 'price' . self::$user_model['type'];
        }

        if (!empty($this['is_kill'])) {
            $kill_price = $data['kill_price'] ?? '0.00';
            $sold_price = empty($this['sold_sku_info']) ? $kill_price : $this['sold_sku_info']['sold_price'];
        } else {
            $sold_price = empty($this['sold_sku_info']) ? $this[$price_field] : $this['sold_sku_info'][$price_field];
        }
        return sprintf('%.2f', $sold_price);
    }

    //计算打车费用
    public function getCalCarMoneyAttr()
    {
        $cal_car_money = $car_money = $this['car_money'];
        $car_money_black = $this['car_money_black'];
        $current_hour = (int)date('H');
        if (($current_hour > 18 || $current_hour <= 5) && !empty($car_money_black)) {
            $cal_car_money = $car_money_black;
        }
        return $cal_car_money;
    }


    public function getImgAttr($value, $data)
    {
        $value = empty($value) ? [] : explode(',', $value);

        return $value;
    }



    public static function onBeforeInsert(Model $model)
    {
        $attr =[];
        if(empty($model['code'])){
            $attr['code'] = self::make_coupon_card();
        }
        $model->setAttrs($attr);
    }

    //商品删除--之后
    public static function onAfterDelete(Model $model)
    {
        //清空-购物车-收藏
        //        UserCartModel::where(['gid'=>$model['id']])->delete();
        //        UserCollModel::where(['gid'=>$model['id']])->delete();
    }


    public static function modifyTags(array $input_data = [])
    {
        $optModel = $input_data['optModel']??'';
        $optQuery = $input_data['optQuery']??[];

        $ids = empty($input_data['ids']) || !is_array($input_data['ids']) ? [] :$input_data['ids'];
        $mode = $input_data['mode']??'';
        $tags = $input_data['tags']??'';
        $tags = empty($tags)?[] : explode(',',$tags);
        if(empty($mode)) throw new \Exception('参数异常:mode');
        //修改数据
        $modifyFun = function(GoodsModel $goods_model)use($mode,$tags){
            $goods_tags = empty($goods_model['tags'])?[]: array_filter(explode(',',$goods_model['tags']));
            if($mode==1){ //覆盖

            }elseif($mode==2){ //追加
                $tags = array_values(array_unique(array_merge($tags,$goods_tags)));
            }elseif($mode==3){ //删除
                $tags = array_values(array_diff($goods_tags,$tags));
            }
            $goods_model->setAttr('tags',empty($tags)?null:','.implode(',',$tags).',');

            $goods_model->save();
        };

        if($optModel=='all'){
            $info = self::getPageData($optQuery);

            if($info instanceof Paginator){
                $optQuery['limit'] = $info->total();
                self::getPageData($optQuery)->each(function($item)use($input_data,$modifyFun){
                    $modifyFun($item);
                });
            }elseif($info instanceof Collection){
                $info->each(function($item)use($input_data,$modifyFun){
                    $modifyFun($item);
                });
            }
        }else{
            if(empty($ids)) throw new \Exception('请选择要操作的对象');
            foreach ($ids as $id){
                $goods_model = GoodsModel::find($id);
                if(empty($goods_model)) continue;

                $modifyFun($goods_model);
            }
        }


    }


    //快捷复制
    public static function copyData(array $input_data = [])
    {
        $id = $input_data['id'] ?? 0;
        if (empty($id)) throw new \Exception('参数异常:id');

        $model_goods = Db::table('goods')->where(['id' => $id])->find();
        if (empty($model_goods)) throw new \Exception('产品不存在');
        $model_goods_sku_mix_price = Db::table('goods_sku_mix_price')->where(['gid' => $model_goods['id']])->select();
        $model_goods_sku_price = Db::table('goods_sku_price')->where(['gid' => $model_goods['id']])->select();
        unset($model_goods['id']);
        $new_model  = new self();
        $new_model->setAttrs($model_goods);
        $new_model->setAttr('code',self::make_coupon_card());
        $new_model->save();
        if (!$model_goods_sku_mix_price->isEmpty()) {
            $model_goods_sku_mix_price->each(function ($item) use ($new_model) {
                unset($item['id']);
                $item['gid'] = $new_model['id'];
                return $item;
            });
            Db::table('goods_sku_mix_price')->insertAll($model_goods_sku_mix_price->toArray());
        }
        if (!$model_goods_sku_price->isEmpty()) {
            $model_goods_sku_price->each(function ($item) use ($new_model) {
                unset($item['id']);
                $item['gid'] = $new_model['id'];
                return $item;
            });
            Db::table('goods_sku_price')->insertAll($model_goods_sku_price->toArray());
        }
    }

    public static function handleSaveData(array $input_data = [])
    {
//        if(empty($input_data['group_cate_id'])) throw new \Exception('请选择分类');
        if(empty($input_data['name'])) throw new \Exception('请输入名字');
        if(empty($input_data['og_price'])) throw new \Exception('请输入产品原价');
        if(empty($input_data['price'])) throw new \Exception('请输入产品售价');
        if(empty($input_data['img'])) throw new \Exception('请上传图片');
        $commission_per = $input_data['commission_per']??'';
        if(!empty($commission_per) && ($commission_per<0 || $commission_per>1) ) throw new \Exception('佣金只能设置在0-1之间');

        $input_data['temp_no'] = strtoupper(str_replace(' ','-',preg_replace('/[^a-zA-z0-9]+/',' ',$input_data['name'])));
        //检查编号是否重复
//        $check_where = [];
//        $check_where[] = ['temp_no','=',$input_data['temp_no']];
//        if(!empty($input_data['id'])){
//            $check_where[] = ['id','<>',$input_data['id']];
//        }
//
//        $exist_goods = self::where($check_where)->find();
//        if(!empty($exist_goods))  throw new \Exception('存在同名商品,请修改商品名');

        //服务地址
        $input_data['ser_locations'] = empty($input_data['ser_locations']) || !is_array($input_data['ser_locations'])? "" : implode(',',$input_data['ser_locations']);

        $group_cid=empty($input_data['group_cate_id'])?[]:explode(',',$input_data['group_cate_id']);
        $input_data['cid'] = $group_cid[0]??0;
        $input_data['ct_id'] = $group_cid[1]??0;

        $input_data['img'] = empty($input_data['img'])?'':(is_array($input_data['img'])?implode(',',$input_data['img']):$input_data['img']);
        //产品标签
//        $input_data['tags'] = !empty($input_data['tags']) && is_array($input_data['tags']) ? ','.implode(',',$input_data['tags']).',' : null;
        $input_data['tags'] = !empty($input_data['tags']) ? preg_replace('/\s+/','',','.$input_data['tags'].',') : null;
        //spu
        $spu = empty($input_data['spu'])?[]:(!is_array($input_data['spu'])?[]:$input_data['spu']);
        $spu_arr = [];
        foreach ($spu as $item){
            if(!empty($item['name']) && !empty($item['value'])){
                $spu_arr[] = $item;
            }
        }
        $input_data['spu'] = $spu_arr;
        //sku处理
        $sku = (empty($input_data['sku']) || !is_array($input_data['sku']))?[]: $input_data['sku'];
        $input_data['sku'] = null;
        $sku_price = (empty($input_data['sku_price']) || !is_array($input_data['sku_price']))?[]: $input_data['sku_price'];
        //sku-mix
        $sku_mix = (empty($input_data['sku_mix']) || !is_array($input_data['sku_mix']))?[]: $input_data['sku_mix'];
        $record_sku_price = [];
        $sku_price_exist_id = [];

        //处理数据
        if(!empty($sku)){
            if(empty($sku_price)){
                $input_data['sku'] = null;
            }else{
                unset($input_data['sku_price']);
                //处理sku问题
                $sku_all_name = [];
                foreach ($sku as &$item){
                    if(empty($item['name']))  throw new \Exception('请检测sku名称问题:1');
                    if(empty($item['content']))  throw new \Exception('sku属性不能为空');
                    $content = array_filter(explode(',',str_replace(' ','',$item['content'])));
                    if(count($content)!=count(array_unique($content))) throw new \Exception('规格【'.$item['name'].'】存不得存在同样sku');
                    $sku_all_name = array_merge($sku_all_name,$content);
                    $content = implode(',',$content);
                    $item['content'] = $content;
                }
                $input_data['sku'] = $sku; //绑定sku
                $input_data['sku_keyword_names'] = empty($sku_all_name)?null:strtoupper(','.implode(',',$sku_all_name).','); //绑定sku
                //处理价格问题
                $sku_price_all_name = [];
                foreach ($sku_price as $vo){
                    $id = $vo['id']??0;
                    if( $id == -1 ) continue;
                    if(empty($vo['name']))  throw new \Exception('请检测sku名称问题');
                    if(empty($vo['price']))  throw new \Exception('请输入sku'.$vo['name'].'的价格');
                    $name = array_filter(explode(',',str_replace(' ','',$vo['name'])));
                    $sku_price_all_name = array_merge($sku_price_all_name,$name);
                    $info=[
                        'name' => implode(',', $name),
                        'og_price' => $vo['og_price']??0,
                        'price' => $vo['price']??0,
//                        'price2' => $vo['price2']??0,
                        'stock' => $vo['stock']??0,
                        'weight' => $vo['weight']??0,
                        'img' => $vo['img']??'',
                        'status' => 1,//启用状态
                    ];
                    if(!empty($vo['id'])){
                        $info['id'] = $id;
                        $sku_price_exist_id[] = $id;
                    }

                    $record_sku_price[] = $info;
                }

                if(array_diff($sku_price_all_name,$sku_all_name) || array_diff($sku_all_name,$sku_price_all_name)){
                    throw new \Exception('请检测sku数据信息异常,请刷新页面重新处理');
                }
            }
        }
        //处理sku_mix
        $sku_mix_price_exist_id = [];
        if(!empty($sku_mix)){
            foreach ($sku_mix as $mix_item){
                $id = $mix_item['id']??0;
                if(!empty($id)){
                    $sku_mix_price_exist_id[] = $id;
                }
                if(empty($mix_item['name']))  throw new \Exception('键输入配料名称');
                if(empty($mix_item['price']))  throw new \Exception('键输入配料价格');
                $mix_item['status'] =  $mix_item['status_bool']==='true'?1:0;//启用状态
            }
        }
        //直接保存信息
        $model = (new self())->actionAdd($input_data);

        //sku处理-开始
        $insert_sku_price_data = [];
        foreach ($record_sku_price as $vo){
            if(!empty($vo['id'])){
                //更新信息
                GoodsSkuPriceModel::where(['id'=>$vo['id']])->update($vo);
            }else{
                $vo['gid'] = $model['id'];
                $insert_sku_price_data[] = $vo;
            }
        }
        //删除不需要的
        $del_where[] = ['gid','=',$model['id']];
        if(!empty($sku_price_exist_id)){
            $del_where[] = ['id','not in',$sku_price_exist_id];
        }
//        dump($del_where);exit;
        GoodsSkuPriceModel::where($del_where)->delete();
        //保留sku数据
        if(count($insert_sku_price_data)){
            GoodsSkuPriceModel::insertAll($insert_sku_price_data);
        }
        //sku处理-结束


        //sku-mix处理-开始
        $insert_sku_mix_price_data = [];
        foreach ($sku_mix as $vo){
            $vo['status'] = $vo['status_bool']==='true'?1:0;//启用状态
            unset($vo['status_bool']);
            if(!empty($vo['id'])){
                //更新信息
                GoodsSkuMixPriceModel::where(['id'=>$vo['id']])->update($vo);
            }else{
                unset($vo['id']);
                $vo['gid'] = $model['id'];
                $insert_sku_mix_price_data[] = $vo;
            }
        }

        //删除不需要的
        $del_where[] = ['gid','=',$model['id']];
        if(!empty($sku_mix_price_exist_id)){
            $del_where[] = ['id','not in',$sku_mix_price_exist_id];
        }
//        dump($del_where);exit;
        GoodsSkuMixPriceModel::where($del_where)->delete();
        //保留sku数据
        if(count($insert_sku_mix_price_data)){
            GoodsSkuMixPriceModel::insertAll($insert_sku_mix_price_data);
        }
        //sku-mix-结束
    }



    /**
     * 获取商品数据
     * @param array $input_data 请求内容
     * @param int|null $limit 页面条数
     * @param UserModel|null $user_model 用户模型
     * @throws
     * @return \think\Paginator
     * */
    public static function getPageData(array $input_data = [], UserModel $user_model = null)
    {
        $limit = $input_data['limit'] ?? null;
        $activeState = $input_data['activeState'] ?? '';

        $whereFnc = $whereFncGoodsCate = $whereFncColor = $whereFncSize = $whereFncStyle = null;
        $whereFncGoodsAttr = null; $whereFncFlag = null;
        $sort_gids_arr =[]; //指定排序功能
        $where = $whereOr = [];
        if(!isset($input_data['ignore_type'])){
            $type = empty($input_data['check_goods_type']) ? 0 : intval($input_data['check_goods_type']);
            $where[] = ['goods_model.type','=',$type];
        }


        if (isset($input_data['id'])) {
            $where[]  = ['goods_model.id', (is_array($input_data['id']) ? 'in' : '='), $input_data['id']];
        }
        if (isset($input_data['check_gift'])) {
            $where[]  = ['goods_model.tags', 'like', '%,gift,%'];
        }

        $cid = $input_data['cid'] ?? 0;
        if (!empty($cid)) {
            $where[] = ['cid', '=', $cid];
        }

        //推广flag
        $cancel_force_order = false;
        $flag = empty($input_data['flag'])?'':$input_data['flag'];
        if(!empty($flag)){
            $platform_tags_model = PlatformTagsModel::where(['flag'=>$flag,'status'=>1])->find();
            if ( empty($platform_tags_model) || empty($platform_tags_model['tags'])) {
                return Paginator::make(null, 1, 1, 0);
            }
            //强制排序
            if(!empty($platform_tags_model['sort_plan'])){
                $force_order_by = PlatformTagsModel::getPropInfo('getSelectSortPlanList',$platform_tags_model['sort_plan'],'sort','value');
            }

            $all_platform_tags = array_filter(array_unique(explode(',',$platform_tags_model['tags'])));
            $regexp_str_arr = [];
            foreach ($all_platform_tags as $item){
                if(empty($item)) continue;
                $regexp_str_arr[] = strtoupper(",$item,");
            }
            $tag_regexp_str = implode('|',$regexp_str_arr);

            if(empty($tag_regexp_str)) {
                return Paginator::make(null,1,1,0);
            }

            $whereFncFlag = function($query)use($tag_regexp_str){
                $where = [] ;
                $where[] =  ['goods_model.tags','REGEXP',$tag_regexp_str];
                $query->whereOr($where);
            };
            if(!empty($platform_tags_model['goods_sort'])){
                $sort_gids_arr = explode('-',$platform_tags_model['goods_sort']);
            }
        }


        $goods_attr = empty($input_data['goods_attr']) || !is_array($input_data['goods_attr']) ? [] :$input_data['goods_attr'];
        if(!empty($goods_attr)){
            $all_platform_tag_ids = GoodsAttrsModel::whereIn('id',$goods_attr)->whereNotNull('tags')->column('distinct tags');
            if(empty($all_platform_tag_ids)){
                return Paginator::make(null, 1, 1, 0);
            }
            $all_platform_tags = PlatformTagsModel::whereIn('id',$all_platform_tag_ids)->column('tags');
            if(empty($all_platform_tags)){
                return Paginator::make(null, 1, 1, 0);
            }
            $all_platform_tags = array_values(array_filter(array_unique(explode(',',implode(',',$all_platform_tags)))));
            $regexp_str_arr = [];

            foreach ($all_platform_tags as $item){
                if(empty($item)) continue;
                $regexp_str_arr[] = strtoupper(",$item,");
            }
            $tag_regexp_str = implode('|',$regexp_str_arr);

            if(empty($tag_regexp_str)) {
                return Paginator::make(null,1,1,0);
            }
            $whereFncGoodsAttr = function($query)use($tag_regexp_str){
                $where = [] ;
                $where[] =  ['goods_model.tags','REGEXP',$tag_regexp_str];
                $query->whereOr($where);
            };
        }

        $goods_cate = empty($input_data['goods_cate']) || !is_array($input_data['goods_cate']) ? [] :$input_data['goods_cate'];
        if(!empty($goods_cate)){
            $where[] = ['cid','in',$goods_cate];
        }

        $ct_id = $input_data['ct_id'] ?? 0;
        if (!empty($ct_id)) {
            $where[] = ['ct_id', '=', $ct_id];
        }

        // 颜色
        $color = empty($input_data['color']) || !is_array($input_data['color']) ? [] :$input_data['color'];
        if(!empty($color)){
            $regexp_str_arr = [];
            foreach ($color as $item){
                $regexp_str_arr[] = strtoupper(",$item,");
            }
            $tag_regexp_str = implode('|',$regexp_str_arr);

            //查看商品的标签
            $whereFncColor= function($query)use($tag_regexp_str){
                $where = [] ;
                $where[] =  ['goods_model.sku_keyword_names','REGEXP',$tag_regexp_str];
                $query->whereOr($where);
            };

        }


        // 尺寸
        $size = empty($input_data['size']) || !is_array($input_data['size']) ? [] :$input_data['size'];
        if(!empty($size)){
            $regexp_str_arr = [];
            foreach ($size as $item){
                $regexp_str_arr[] = strtoupper(",$item,");
            }
            $tag_regexp_str = implode('|',$regexp_str_arr);

            //查看商品的标签
            $whereFncSize= function($query)use($tag_regexp_str){
                $where = [] ;
                $where[] =  ['goods_model.sku_keyword_names','REGEXP',$tag_regexp_str];
                $query->whereOr($where);
            };
        }

        // 标签
        $tag_id = empty($input_data['tag_id']) ? '' : $input_data['tag_id'];

        if(!empty($tag_id)){
            //查询商品分类有这些标签的分类id
            $all_tags = WebMenuModel::where(['id'=>$tag_id])->value('tags');
            $all_tags = empty($all_tags)?[] : explode(",", $all_tags);
            $regexp_str_arr = [];

            foreach ($all_tags as $item){
                if(empty($item)) continue;
                $regexp_str_arr[] = strtoupper(",$item,");
            }
            $tag_regexp_str = implode('|',$regexp_str_arr);
            if(empty($tag_regexp_str)) {
                return Paginator::make(null,1,1,0);
            }
            $all_goods_cate_ids = GoodsCateModel::where([
                ['status','=',1],
                ['tags','REGEXP',$tag_regexp_str],
            ])->column('id');

            //查看商品的标签

            $whereFnc = function($query)use($tag_regexp_str,$all_goods_cate_ids){
                $where = [] ;
                $where[] = [ 'tags','REGEXP',$tag_regexp_str ];
                if(!empty($all_goods_cate_ids)){
                    $where[] = [ 'cid','in',$all_goods_cate_ids ];
                    $where[] = [ 'ct_id','in',$all_goods_cate_ids ];
                }
                $query->whereOr($where);
            };



        }

        $style = empty($input_data['style']) || !is_array($input_data['style']) ? [] :$input_data['style'];
        if(!empty($style)){
            $all_tags = GoodsAttrsModel::whereIn('id',$style)->column('tags');
            $all_tags_data = [];
            foreach ($all_tags as $item){
                $all_tags_data = array_unique(array_merge($all_tags_data,$item));
            }
            $regexp_str_arr = [];
            foreach ($all_tags_data as $item){
                $regexp_str_arr[] = ",$item,";
            }
            $tag_regexp_str = implode('|',$regexp_str_arr);
            //查询商品分类有这些标签的分类id
            $all_goods_cate_ids = GoodsCateModel::where([
                ['status','=',1],
                ['tags','REGEXP',$tag_regexp_str],
            ])->column('id');

            //查看商品的标签
            $whereFncStyle = function($query)use($tag_regexp_str,$all_goods_cate_ids){
                $where = [] ;
                $where[] = [ 'tags','REGEXP',$tag_regexp_str ];
                if(!empty($all_goods_cate_ids)){
                    $where[] = [ 'cid','in',$all_goods_cate_ids ];
                    $where[] = [ 'ct_id','in',$all_goods_cate_ids ];
                }
                $query->whereOr($where);
            };


        }


        $keyword = $input_data['keyword'] ?? '';
        if (!empty($keyword)) {
            $where[] = ['goods_model.name', 'like', '%' . $keyword . '%'];
        }

        $keyword_sku = $input_data['keyword_sku'] ?? '';
        if (!empty($keyword_sku)) {
            $where[] = ['goods_model.no|goods_model.code', 'like', '%' . $keyword_sku . '%'];
//            $keyword_sku = explode(',', strtoupper($keyword_sku));
//            $regexp_str_arr = [];
//            foreach ($keyword_sku as $item){
//                $regexp_str_arr[] = strtoupper(",$item,");
//            }
//            $tag_regexp_str = implode('|',$regexp_str_arr);
//
//            $where[] = ['goods_model.sku_keyword_names', 'REGEXP',  $tag_regexp_str];
        }
//        dump($where);exit;
        $keyword_tags = $input_data['keyword_tags'] ?? '';
        if (!empty($keyword_tags)) {
            $keyword_tags = explode(',',$keyword_tags);
            $regexp_str_arr = [];
            foreach ($keyword_tags as $item){
                $regexp_str_arr[] = strtoupper(",$item,");
            }
            $tag_regexp_str = implode('|',$regexp_str_arr);

            $where[] = ['goods_model.tags', 'REGEXP',  $tag_regexp_str];
        }

        $state = $input_data['state'] ?? 'all';
        if ($state == 'up') {
            //上架
            $where[] = ['goods_model.status', '=', 1];
        } elseif ($state == 'down') {
            //下架
            $where[] = ['goods_model.status', '=', 2];
        } elseif ($state == 'no_stock') {
            //下架
            $where[] = ['goods_model.stock', '=', 0];
        }

        if (app()->http->getName() != 'admin' && !isset($input_data['ignore_status'])) {
            $where[] = ['goods_model.status', '=', 1];
        }

        $cate_ids = empty($input_data['cate_ids']) || !is_array($input_data['cate_ids']) ? [] : $input_data['cate_ids'];
        if (!empty($cate_ids)) {
            $where[] = ['cid', 'in', $cate_ids];
        }

        //价格区间
        $money_start = $input_data['money_start'] ?? '';
        $money_end = $input_data['money_end'] ?? '';
        if ($money_start > 0 && $money_end > 0) {
            $where[] = [Db::raw('if(linkSkuPriceOne.price > 0 ,linkSkuPriceOne.price,goods_model.price )'), '>=', $money_start];
            $where[] = [Db::raw('if(linkSkuPriceOne.price > 0 ,linkSkuPriceOne.price,goods_model.price )'), '<=', $money_end];
        } elseif ($money_start > 0) {
            $where[] = [Db::raw('if(linkSkuPriceOne.price > 0 ,linkSkuPriceOne.price,goods_model.price )'), '>=', $money_start];
        } elseif ($money_end > 0) {
            $where[] = [Db::raw('if(linkSkuPriceOne.price > 0 ,linkSkuPriceOne.price,goods_model.price )'), '<=', $money_end];
        }

        $check_type = $input_data['check_type']??'';
        if ($check_type == 'new_in') { //新品
            $input_data['order_field'] = 'id';
        } elseif($check_type=='best_seller'){ //销售最好
            $input_data['order_field']="sold_num";
            $input_data['order_sort']="desc";
        } elseif($check_type=='mens_shirts'){ //T恤

        }

        $check_order_field = $input_data['check_order_field']??'';
        if($check_order_field=='price-low'){
            $cancel_force_order = true; //取消强制排序
            $input_data['order_field'] = 'price';
            $input_data['order_sort'] = 'asc';
        }elseif($check_order_field=='price-high'){
            $cancel_force_order = true;
            $input_data['order_field'] = 'price';
            $input_data['order_sort'] = 'desc';

        }

        //处理排序
        $limit_order_field = ['sort', 'sold_num', 'views', 'update_time', 'price','id'];
        $order_field = $input_data['order_field'] ?? '';
        $order_field = !in_array($order_field, $limit_order_field) ? 'sort' : $order_field;
        $order_sort = $input_data['order_sort'] ?? '';
        $order_sort = $order_sort == 'desc' ? 'desc' : 'asc';
        $order = $order_field . ' ' . $order_sort;
        $model = self::alias('goods_model')->with(['linkKill', 'linkCate', 'linkSkuPrice', 'linkSkuTemp']);


        $kill_at = $input_data['kill_at'] ?? 0;
        if (!empty($kill_at)) {
            //绑定秒杀类型
            self::$kill_at = $kill_at;
            $all_goods = GoodsKillModel::where(['at' => $kill_at, 'is_open' => 1])->column('gid');
            if (empty($all_goods)) {
                return Paginator::make(null, 1, 1, 0);
            } else {
                $where[] = ['goods_model.id', 'in', $all_goods];
            }
        }

        if (!empty($input_data['self_up'])) { //为你推荐

        }

        if (!empty($input_data['is_new'])) { //推荐/新品
            $where[] = ['goods_model.is_new', '=', 1];
        }
        if (!empty($input_data['is_up'])) { //推荐/新品
            $where[] = ['goods_model.is_up', '=', 1];
        }

        $link_price_where = "";
        if ($order_field == 'price' || $order_field == 'price_desc' || $order_field == 'price_asc') {
            if ($order_field == 'price_desc') {
                $_order_sort = 'desc';
            } elseif ($order_field == 'price_asc') {
                $_order_sort = 'asc';
            }
            $order = 'cond_price ' . (empty($_order_sort) ? $order_sort : $_order_sort );
        }

        if ($money_start > 0 && $money_end > 0) {
            $link_price_where = " and price >= $money_start and price <= $money_end";
        } elseif ($money_start > 0) {
            $link_price_where = " and price >= $money_start";
        } elseif ($money_end > 0) {
            $link_price_where = " and price <= $money_end";
        }

        $model = $model->withJoin('linkSkuPriceOne', 'left');
        $join_cond = $model->getOptions('join');
        if(isset($_order_sort)){
            $join_cond[0][2] .= ' and `linkSkuPriceOne`.`id`= (SELECT id from goods_sku_price s where s.gid=`goods_model`.`id` ' . $link_price_where . '  ORDER BY price ' . $order_sort . ' limit 1)';
        }else{
            $join_cond[0][2] .= ' and `linkSkuPriceOne`.`id`= (SELECT id from goods_sku_price s where s.gid=`goods_model`.`id` ' . $link_price_where . '   limit 1)';
        }
        $model->setOption('join', $join_cond);

        //按指定商品排序
        $sort_gids = empty($input_data['sort_gids'])?[]: explode("-",$input_data['sort_gids']);
        $sort_gids = array_merge($sort_gids,$sort_gids_arr);
//        dump($sort_gids);exit;

        if(!$cancel_force_order && !empty($force_order_by)){
            $order = $force_order_by;
        }

        if(!empty($sort_gids)){
            $sort_gids = array_filter($sort_gids,function($item){
                $num= intval(trim($item));
                return !empty($num) && $num>0;
            });
            $sort_gids = array_reverse($sort_gids);
            $sort_gids_str = implode(',',$sort_gids);
//            dump($sort_gids_str);exit;
            if(!empty($sort_gids_str)){

                if(!empty($order)){
                    $order = Db::raw("-find_in_set(goods_model.id, '".$sort_gids_str."') asc,".$order);
                }else{
                    $order = Db::raw("-find_in_set(goods_model.id, '".$sort_gids_str."') asc");
                }
            }
        }



        if($activeState=='user_up'){ //用户推荐
            $order = Db::raw('rand()');
        }
//        dump($where,$order);exit;
        //获取当前秒杀时间段
        //        if(self::$kill_at<0){
        //            $info = TimeActivity::getRunning();
        //            self::$kill_at = $info['value']??0;
        //        }

        //        dump($where);exit;
        $model = $model
            ->field(['if(linkSkuPriceOne.price > 0 ,linkSkuPriceOne.price,goods_model.price )' => 'cond_price'])
            ->where($where)
            ->where($whereFnc)
            ->where($whereFncGoodsCate)
            ->where($whereFncColor)
            ->where($whereFncSize)
            ->where($whereFncStyle)
            ->where($whereFncGoodsAttr)
            ->where($whereFncFlag)
            ->where(function($query)use($whereOr){
                $query->whereOr($whereOr);
            })
            ->order($order)->paginate($limit)->each(function ($item, $index) {
            //            $item['is_kill'] = 0; //是否在秒杀中.....
            //            $linkKill = $item->getRelation('linkKill');
            //
            //            //获取当前正在进行得秒杀商品
            //            if(!empty($linkKill)){
            //                foreach ($linkKill as $vo){
            //                    if($vo['at']==self::$kill_at){ //当前选中
            //                        $item['is_kill'] = TimeActivity::isRunning(self::$kill_at);
            //
            //                        if($vo['is_open']){  //开启
            //                            if(empty($vo['sku_id'])){
            //                                $item['kill_price'] = $vo['price'];
            //                                $item['kill_stock'] = $vo['stock'];
            //                            }else{
            //                                foreach ($item['linkSkuPrice'] as $sku_price){
            //                                    if($vo['sku_id']==$sku_price['id']){
            //                                        //绑定秒杀sku
            //                                        empty($item->sku_id) && $item->sku_id = $vo['sku_id'];
            //                                        $sku_price['kill_price'] = $vo['price'];
            //                                        $sku_price['kill_stock'] = $vo['stock'];
            //                                        break;
            //                                    }
            //                                }
            //                            }
            //                        }
            //                    }
            //                }
            //            }
        });


        return $model;
    }

    public function getSkuPriceAttr()
    {
        $linkSkuPrice = $this->getRelation('linkSkuPrice');
        $sku_price = [];
        if (!empty($linkSkuPrice)) {
            foreach ($linkSkuPrice as $vo) {
                if (app()->http->getName() == 'admin') {
                    $sku_price[] = $vo->apiFullInfo();
                } else {
                    $sku_price[] = $vo->apiNormalInfo();
                }
            }
        }
        return $sku_price;
    }

    public function apiFullInfo()
    {

        $linkCate = $this->getRelation('linkCate');


        $sku_img = empty($this['sku_img']) ? [] : json_decode($this['sku_img'], true);
        return array_merge($this->apiNormalInfo(), [
            'img' => $this['img'],
            'no' => $this['no'],
            'sku_img' => empty($sku_img) ? [] : $sku_img,
            'status_bool' => $this['status'] == 1,
            'status' => $this['status'],
            'status_name' => self::getPropInfo('fields_status', $this['status'], 'name'),
            'intro' => (string)$this->getAttr('intro'),
            'buy_intro' => (string)$this->getAttr('buy_intro'),
            'send_intro' => (string)$this->getAttr('send_intro'),
            'content' => (string)$this->getAttr('content'),
            'spu' => $this->getAttr('spu'),
            'sku' => $this->getAttr('sku'),
            'sku_price' => $this['sku_price'],
            'sort' => (int)$this['sort'],    //排序
            'update_time' => (string)$this['update_time'],    //排序
            'score' => $this['score'],
            'weight' => (int)$this['weight'],//重量
            'is_new' => (int)$this['is_new'],
            'is_up' => (int)$this['is_up'],
            'ser_locations' => $this['ser_locations'],
            'tags' => $this['tags'],
            'meta_title' => (string)$this['meta_title'],
            'meta_desc' => (string)$this['meta_desc'],
            'meta_key' => (string)$this['meta_key'],

            //分类
            'group_cate_id' => (string)$this['group_cate_id'],
            'cid' => (string)$linkCate['id'],
            'cate_name' => (string)$linkCate['name'],
        ],parent::apiFullInfo());
    }

    //api详情id
    public function apiDetailInfo()
    {
        $is_kill = empty($this['is_kill']) ? 0 : 1;

        return array_merge($this->apiNormalInfo(), [
            'intro' => (string)$this->getAttr('intro'),
            'content' => (string)$this->getAttr('content'),

            'buy_intro' => (string)$this->getAttr('buy_intro'),
            'send_intro' => (string)$this->getAttr('send_intro'),


            'reduce_second' => $is_kill ? TimeActivity::getRunning('reduce_second') : 0, //活动倒计时
        ]);
    }


    //获取商品基本信息
    public  function apiNormalInfo()
    {
        $sold_sku_info = $this['sold_sku_info'];

        $is_kill = empty($this['is_kill']) ? 0 : 1;

        $linkSkuPrice = $this->getRelation('linkSkuPrice');
        $sku_price = [];
        if (!empty($linkSkuPrice)) {
            foreach ($linkSkuPrice as $vo) {
                //                if($vo['status']==1){
                $sku_price[] = $vo->apiNormalInfo();
                //                }
            }
        }
        $data = [
            'id' => (int)$this['id'],
            'cover_img' => (string)$this['cover_img'],
            'cover_img_t' => (string)$this['cover_img_t'],
            'spe_img' => (string)$this['spe_img'],
            'group_no' => (string)$this['group_no'],
            'name' => (string)$this['name'],
            'sub_name' => (string)$this['sub_name'],
            'price' => (string)$this['price'],          //标价 售价
            'sold_price' => (string)$this['sold_price'],          //售价
            'og_price' => (string)$this['og_price'],    //原价
            'stock' => (int)$this['stock'],    //库存
            'weight' => (int)$this['weight'],    //重量
            'freight_money' => $this['freight_money'],    //运费
            'sold_num' => (int)$this['sold_num'],    //销量
            'is_gift' => $this['is_gift'],    //礼品产品

            'sold_state' => $this['sold_state'], //销售状态 1 空库存可售 非1 空库存不可售
            'sku_id' => empty($sold_sku_info) ? 0 : (int)$sold_sku_info['id'],
            'sku_name' => empty($sold_sku_info) ? '' : (string)$sold_sku_info['name'],
            'sku_img' => empty($sold_sku_info) ? '' : (string)$sold_sku_info['img'],
            'sku_weight' => empty($sold_sku_info) ? '' : (string)$sold_sku_info['weight'],
            'spu' => empty($this['spu']) || !is_array($this['spu']) ? [] : $this['spu'],
            'sku_attr' => $this->getAttr('sku_attr'),
            'sku_price' => $sku_price,
            'sku_attr_img'=> $this['sku_attr_img'],


            'is_kill' => $is_kill, //是否进行秒杀活动中...

        ];

        $get_data = $this->getData();
        if (!empty($this['kill_price'])) {
            $data['kill_price'] = $this['kill_price'];
        }

        if (!empty($this['kill_stock'])) {
            $data['kill_stock'] = $this['kill_stock'];
        }
        $buy_num = $this->getAttr('buy_num');
        if (!empty($buy_num)) {
            $data['buy_num'] = $buy_num;
        }
        $is_checked = $this->getAttr('is_checked');
        if (isset($get_data['is_checked'])) {
            $data['is_checked'] = $get_data['is_checked'];
        }
        $cart_id = $this->getAttr('cart_id');
        if (!empty($cart_id)) {
            $data['cart_id'] = $cart_id;
        }
        $cart_logo = $this->getAttr('cart_logo');
        if (!empty($cart_logo)) {
            $data['cart_logo'] = $cart_logo;
        }
        $cart_logo_list = $this->getAttr('cart_logo_list');
        if (!empty($cart_logo_list)) {
            $data['cart_logo_list'] = $cart_logo_list;
        }
        $cart_list = $this->getAttr('cart_list');
        if (!empty($cart_list)) {
            $data['cart_list'] = $cart_list;
        }
        $cart_remark = $this->getAttr('cart_remark');
        if (!empty($cart_remark)) {
            $data['cart_remark'] = $cart_remark;
        }
        return $data;
    }


    public function linkCate()
    {
        return $this->belongsTo(GoodsCateModel::class, 'cid');
    }
    public function linkSkuPrice()
    {
        return $this->hasMany(GoodsSkuPriceModel::class, 'gid')->order('id asc');
    }

    public function linkSkuTemp()
    {
        return $this->belongsTo(GoodsSkuTempModel::class, 'sku_temp_id');
    }


    public function linkSkuPriceOne()
    {
        return $this->hasOne(GoodsSkuPriceModel::class, 'gid')->order('');
    }


    //秒杀产品
    public function linkKill()
    {
        return $this->hasMany(GoodsKillModel::class, 'gid');
    }
}
